package com.platform.api;

import com.google.gson.Gson;

import java.io.Serializable;

public class Page implements Serializable {

    private static final int MAX_PAGE_SIZE = 1000;
    public static final int DEFAULT_PAGE_SIZE = 10;
    public static final int DEFAULT_PAGE_NUM = 1;
    /**
     * 已知数据
     * 当前页,从请求那边传过来.
     */
    private int pageNum = Page.DEFAULT_PAGE_NUM;
    /**
     * 每页显示的数据条数。默认二十条
     */
    private int pageSize = Page.DEFAULT_PAGE_SIZE;
    /**
     * 总的记录条数。查询数据库得到的数据
     */
    private int totalRecord;

    /**
     * 需要计算得来
     * 总页数，通过totalRecord和pageSize计算可以得来
     */
    private int totalPage;
    /**
     * 开始索引，也就是我们在数据库中要从第几行数据开始拿，有了startIndex和pageSize，
     * 就知道了limit语句的两个数据，就能获得每页需要显示的数据了
     */
    private int startIndex;

    /**
     * 放入入参时默返回这个方法
     */
    public Page() {

    }

    public Page(int pageNum) {
        this.pageNum = pageNum;
    }

    public Page(int pageNum, int pageSize) {
        this.pageNum = pageNum;
        this.pageSize = pageSize;
    }

    /**
     * 通过pageNum，pageSize，totalRecord计算得来tatalPage和startIndex
     * 构造方法中将pageNum，pageSize，totalRecord获得
     */
    public Page(int pageNum, int pageSize, int totalRecord) {
        this.pageNum = pageNum;
        this.pageSize = pageSize;
        this.totalRecord = totalRecord;
    }

    public int getPageNum() {
        return pageNum;
    }

    public void setPageNum(int pageNum) {
        this.pageNum = pageNum;
    }

    public int getPageSize() {
        return pageSize > MAX_PAGE_SIZE ? MAX_PAGE_SIZE : pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getTotalRecord() {
        return totalRecord;
    }

    public void setTotalRecord(int totalRecord) {
        this.totalRecord = totalRecord;
    }

    public int getTotalPage() {
        //totalPage 总页数
        if (totalRecord % pageSize == 0) {
            //说明整除，正好每页显示pageSize条数据，没有多余一页要显示少于pageSize条数据的
            this.totalPage = totalRecord / pageSize;
        } else {
            //不整除，就要在加一页，来显示多余的数据。
            this.totalPage = totalRecord / pageSize + 1;
        }
        return totalPage;
    }

    public int getStartIndex() {
        this.startIndex = (this.getPageNum() - 1) * pageSize + 1;
        return this.startIndex;
    }

    @Override
    public String toString() {
        return new Gson().toJson(this);
    }
}
